#include <iostream>
#include <string>
#include <algorithm>
#include <cmath>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <TROOT.h>
#include <TFile.h>
#include <TTree.h>
#include <TSQLServer.h>
#include <TSQLResult.h>
#include <TSQLRow.h>
#include <TClonesArray.h>

#include "GeomSvc.h"
#include "TriggerRoad.h"

using namespace std;

TSQLResult *makeQuery(TSQLServer *con, string query)
{
  //cout << query << endl;
  return con->Query(query.c_str());
}

int main(int argc, char **argv)
{
  cout << "Exporting Run: " << argv[1] << " to ROOT file: " << argv[2] << endl;

  GeomSvc *p_geomSvc = GeomSvc::instance();
  p_geomSvc->init("geometry_R962");

  Int_t nHits;
  Int_t detectorID[5000];
  Int_t elementID[5000];
  Double_t x[5000];
  Double_t y[5000];
  
  TFile *saveFile = new TFile(argv[2], "recreate");
  TTree *saveTree = new TTree("save", "save");
 
  saveTree->Branch("nHits", &nHits, "nHits/I");
  saveTree->Branch("detectorID", detectorID, "detectorID[nHits]/I");
  saveTree->Branch("elementID", elementID, "elementID[nHits]/I");
  saveTree->Branch("x", x, "x[nHits]/D");
  saveTree->Branch("y", y, "y[nHits]/D");

  ///Connect to the SQL databases
  //TSQLServer *con = TSQLServer::Connect("mysql://seaquel.physics.illinois.edu", "seaguest","qqbar2mu+mu-");
  TSQLServer *con = TSQLServer::Connect("mysql://140.109.102.242", "admin","scientific"); 
  const char *buf1 = "SELECT eventID FROM %s.Event ORDER BY eventID LIMIT %d";
  const char *buf2 = "SELECT detectorName,elementID,xAtDigiPlane,yAtDigiPlane FROM %s.mDigiHit WHERE eventID=%d AND (detectorName LIKE 'H__'"
   " OR detectorName LIKE 'H4___') ORDER BY zAtDigiPlane";

  char query[500];
  sprintf(query, buf1, argv[1], atoi(argv[3])); 
  TSQLResult *res_event = makeQuery(con, query);

  UInt_t nEntries = res_event->GetRowCount();
  cout << "Totally " << nEntries << " dimuon pairs in this run" << endl;
  for(UInt_t i = 0; i < nEntries; i++)
    {
      if(i % 1000 == 0)
	{
	  cout << "Converting event " << i << endl;
	}

      TSQLRow *row_event = res_event->Next();
      Int_t eventID = atoi(row_event->GetField(0));

      sprintf(query, buf2, argv[1], eventID);
      TSQLResult *res_hodo = makeQuery(con, query);

      nHits = res_hodo->GetRowCount();
      for(Int_t j = 0; j < nHits; j++)
	{
	  TSQLRow *row_hodo = res_hodo->Next();

	  string detectorName(row_hodo->GetField(0));
	  Int_t eID = atoi(row_hodo->GetField(1));
	  p_geomSvc->toLocalDetectorName(detectorName, eID);
	  Int_t dID = p_geomSvc->getDetectorID(detectorName);
	  x[j] = atof(row_hodo->GetField(2));
	  y[j] = atof(row_hodo->GetField(3));

	  detectorID[j] = dID;
	  elementID[j] = eID;
	  delete row_hodo;
	}

      saveTree->Fill();

      delete row_event;
      delete res_hodo;
    }

  delete res_event;
  delete con;

  saveFile->cd();
  saveTree->Write();
  saveFile->Close();
  
  return 1;
}
